package com.gac.basedownload;

import android.util.Log;

import com.gac.basedownload.model.DownloadRecord;
import com.gac.basedownload.model.FileRecord;

import java.io.File;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class DownloadTask extends Thread {
    private FileRecord mFileRecord;
    private DownloadRecord mDownloadRecord;
    private boolean isPause = false;
    private ThreadDownloadListener mListener;
    //额外的请求头
    private Map<String,String> requestPropertyMap = new HashMap<>();

    public DownloadTask(FileRecord fileRecord,DownloadRecord downloadRecord,ThreadDownloadListener listener){
        mFileRecord = fileRecord;
        mDownloadRecord = downloadRecord;
        mListener = listener;
    }
    @Override
    public void run() {
        long total = 0;
        HttpURLConnection connection = null;
        if(mFileRecord == null || mDownloadRecord == null){
            return;
        }
        int responseCode = 200;
        try{
            URL url = new URL(mFileRecord.getUrl());
            connection = (HttpURLConnection)url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(10*1000);

            //添加额外头部参数
            if(requestPropertyMap.size()>0){

                for (Map.Entry<String, String> stringStringEntry : requestPropertyMap.entrySet()) {
                    connection.setRequestProperty(stringStringEntry.getKey(),stringStringEntry.getValue());
                }

            }

            connection.setRequestProperty("Connection", "Keep-Alive");

            //加上这个头部，则可以防止getContentLength()为-1
            connection.setRequestProperty("Accept-Encoding", "identity");
            //查询数据库是否存在断点记录
            //startIndex = Jarvis.getDownloadRecordDBHelper().getStartIndexOfDownloadRecord(this.url, threadId, startIndex);


            connection.setRequestProperty("Accept-Ranges", "bytes");

            Log.e("gacmy","start---"+mDownloadRecord.getStartIndex()+"  end:::"+mDownloadRecord.getEndIndex());
            //设置分段下载的头信息  Range:做分段
            connection.setRequestProperty("Range", "bytes=" + mDownloadRecord.getStartIndex() + "-" + mDownloadRecord.getEndIndex());


            connection.connect();

            responseCode = connection.getResponseCode();

            //不支持断点续传
            if(responseCode == 200){
                mDownloadRecord.setStartIndex(0);
            }

            if (responseCode == 206 || responseCode == 200) {


                InputStream inputStream = connection.getInputStream();
                File file = new File(mFileRecord.getSavePath());
                if (!file.exists()) {
                    file.mkdirs();
                }

                String totalPath = mFileRecord.getSavePath();

                RandomAccessFile randomAccessFile = new RandomAccessFile(totalPath, "rw");

                //设置该分段的文件起点位置
                randomAccessFile.seek(mDownloadRecord.getStartIndex());


                byte[] buffer = new byte[1024];
                int length = -1;



                while ((length = inputStream.read(buffer)) != -1 && !isPause) {
                    //写入该文件
                    randomAccessFile.write(buffer, 0, length);
                    total += length;
                    mDownloadRecord.setDownloadLen(total);
                    if(mListener != null){
                        mListener.onDownload(total,mDownloadRecord);
                    }

                }


                randomAccessFile.close();
                inputStream.close();
                if(mListener != null){
                    mListener.onFinish(total,mDownloadRecord);
                }

                if (responseCode == 206) {
                   // Log.e("gacmy",threadId+":::一个线程下载完成");
                    //保存当前线程已下载的文件大小
                    //Jarvis.getDownloadRecordDBHelper().saveDownloadedFileLength(url, threadId, total);
                    //将当前终止的文件位置插入数据库
//                DownloadHistoryDBHelper.DownloadRecord downloadRecord = new DownloadHistoryDBHelper.DownloadRecord(url, threadId, startIndex + total, endIndex);

                    //将记录保存到数据库
//                Friday.getDownloadRecordDBHelper().updateDownloadRecord(downloadRecord);
                   // Jarvis.getDownloadRecordDBHelper().saveOrUpdateDownloadRecord(url, threadId, startIndex + total, endIndex);

                }
                //如果手动暂停，终止时
//                if (isPause) {
//
//
//                    //断开网络连接
//                    connection.disconnect();
//
//                    if (threadDownloadListener != null) {
//                        threadDownloadListener.onPause();
//                    }
////                        break;
//                }else{
//                    downloadState=DownloadState.FINISH;
//
//                }
//
//                if (threadDownloadListener != null) {
//                    Log.e("gacmy","thread download finish");
//                    threadDownloadListener.onFinish(total);
//                }else {
//                    Log.e("gacmy","thread download listener is null");
//
//                }
//
//            } else {
//                if (threadDownloadListener != null) {
//                    Log.e("gacmy","responsecode is not 200 || 206");
//                    threadDownloadListener.onPause();
//                    threadDownloadListener.onFail();
//                }
//                downloadState =DownloadState.FAIL;
//
            }

        }catch (Exception e){
            if(mListener != null){
                mListener.onFail();
            }
        }
    }


    public interface ThreadDownloadListener {

        void onDownload(long currentDownloadSize,DownloadRecord record);

        void onFinish(long total,DownloadRecord record);

        void onPause();

        void onFail();

    }
}
